package com.nantai.jiafang.nantaijiafang.zhijian.fragment;

import android.app.DatePickerDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;

import com.blankj.utilcode.util.StringUtils;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.ViewModel.Zhijian_Net;
import com.nantai.jiafang.nantaijiafang.activity.adapter.FilterAdapter;
import com.nantai.jiafang.nantaijiafang.base.BaseFragment;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.HeTongHao;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.Item.HeardItem_2;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.PurchaseInfo;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.ReasonRemark;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.Tip;
import com.nantai.jiafang.nantaijiafang.databinding.FragmentZhiJianAddBinding;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.android.volley.VolleyLog.TAG;

/**
 * Created by Administrator on 2017/11/7.
 */

public class ZhijianFragment_add extends BaseFragment<FragmentZhiJianAddBinding> implements View.OnClickListener {
    private FragmentZhiJianAddBinding binding;
    private ArrayList<String> producerNames=new ArrayList<>();
    private ArrayList<String> producerCodes=new ArrayList<>();
    private String producerCode;
    private String reasonRemark;
    private int reasonType;
    private ArrayList<String> getEngineerInfocodes=new ArrayList<>();
    private String engineerNocode;
    private ArrayList<String> getEngineerInfonames=new ArrayList<>();
    private ArrayList<String> EngineerNos=new ArrayList<>();
    private List<String> reasonMarkList=new ArrayList<>();

    private  ArrayAdapter<String> reasonMarkadapter;
    private  ArrayAdapter<String> supplierInfoadapter;
    private FilterAdapter<String>  produceradapter;
    private ArrayList<String> fabricCodes=new ArrayList<>();
    private String fabricCode;
    private  Calendar calendar = Calendar.getInstance();
    private HeardItem_2 heardItem_2=null;
    private String creater,guid,id,offid,OffCount,formnumber,supplierCode;
    public static ZhijianFragment_add initZhijianFragment_add(HeardItem_2 heardItem_2){
        ZhijianFragment_add zhijianFragment_add=new ZhijianFragment_add();
        zhijianFragment_add.setheardItem_2(heardItem_2);
        return zhijianFragment_add;
    }
    private void setheardItem_2(HeardItem_2 heardItem_2){
        this.heardItem_2=heardItem_2;
    }
    @Override
    public int setlayoutid() {
        return R.layout.fragment_zhi_jian_add;
    }
    @Override
    public void initUI(FragmentZhiJianAddBinding binding) {
        this.binding=binding;
        String year =String.valueOf(calendar.get(Calendar.YEAR)) ;//年份
        String month =String.valueOf( calendar.get(Calendar.MONTH)+1); //月份
        String date =String.valueOf( calendar.get(Calendar.DATE));//日期
        String datetime=year+"-"+month+"-"+date;
        binding.detailInspectTime.setText(datetime);
        binding.detailProductTime.setText(datetime);
        guid="";
        id="";
        offid="";
        OffCount="";
        formnumber="";
        supplierCode="";
         if (heardItem_2 != null) {
             Log.e(TAG, "initUI: 123" );
            if (heardItem_2.getInsType().equals("内检")) {
                binding.detailInsType.setSelection(1);
            }else{
                binding.detailInsType.setSelection(0);
            }
            if (heardItem_2.getInspectResult().equals("合格")) {
                binding.detailInspectResult.setSelection(1);
                binding.detailReasonMark.setVisibility(View.VISIBLE);
                binding.detailReasonMarkSp.setVisibility(View.GONE);
                reasonType =0;
            }else if (heardItem_2.getInspectResult().equals("不合格")){
                binding.detailInspectResult.setSelection(2);
                binding.detailReasonMark.setVisibility(View.GONE);
                binding.detailReasonMarkSp.setVisibility(View.VISIBLE);
                reasonType = 1;
            }else if("二等品".equals(heardItem_2.getInspectResult())){
                binding.detailInspectResult.setSelection(3);
                binding.detailReasonMark.setVisibility(View.GONE);
                binding.detailReasonMarkSp.setVisibility(View.VISIBLE);
                reasonType =1;
            }else{
                binding.detailInspectResult.setSelection(0);
                binding.detailReasonMark.setVisibility(View.VISIBLE);
                binding.detailReasonMarkSp.setVisibility(View.GONE);
                reasonType =0;
            }

            if("自用".equals(heardItem_2.getUsefor())){
                binding.detailUsefor.setSelection(0);
            }else if("GA".equals(heardItem_2.getUsefor())){
                binding.detailUsefor.setSelection(1);
            }

           binding.detailContractNo.setText(heardItem_2.getContractNo());
            binding.detailSamplingNo.setText(heardItem_2.getSamplingNo());
            binding.detailBatchNumber.setText(heardItem_2.getBatchNumber());
            binding.detailProductTime.setText(heardItem_2.getProductTime());
            binding.detailInspectTime.setText(heardItem_2.getInspectTime());
            binding.detailColor.setText(heardItem_2.getColor());
            binding.detailRemark.setText(heardItem_2.getRemark());
            binding.detailGateWidth.setText(heardItem_2.getGateWidth());
            creater=heardItem_2.getCreateUser();
            getdata(heardItem_2.getContractNo());
           guid=heardItem_2.getGuid();
            id=heardItem_2.getID();
            offid=heardItem_2.getOffID();
            OffCount=heardItem_2.getOffCount();
            formnumber=heardItem_2.getFormNumber();
            supplierCode=heardItem_2.getSupplierCode();
             reasonRemark = heardItem_2.getResultDes();
        }else{
            creater=Data.username;
            binding.detailInspectorName.setText(Data.ZHIJIAN_Account);
        }
      FilterAdapter arrayAdapter = new FilterAdapter<String>(getContext(), Data.hetonghao);
        binding.detailContractNo.setAdapter(arrayAdapter);

        binding.detailFabricName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                fabricCode=fabricCodes.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        binding.detailContractNo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s=(String)parent.getItemAtPosition(position);
                getdata(s);
            }
        });
        binding.detailProducerName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                producerCode=producerCodes.get(produceradapter.getMposition(position));
            }
        });
        binding.detailEngineerNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                engineerNocode= getEngineerInfocodes.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        binding.detailInspectResult.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               String value=  (String)parent.getItemAtPosition(position);
                if(position == 0 || position == 1){
                    binding.detailReasonMark.setVisibility(View.VISIBLE);
                    binding.detailReasonMarkSp.setVisibility(View.GONE);
                    reasonType = 0;
                }else{
                    binding.detailReasonMark.setVisibility(View.GONE);
                    binding.detailReasonMarkSp.setVisibility(View.VISIBLE);
                    reasonType = 1;
                    getReasonRemark(value,reasonRemark);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
//        binding.detailInspectResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                System.out.print(position);
//            }
//        });

        binding.detailReasonMarkSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                reasonRemark =  (String)parent.getItemAtPosition(position);

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });



        binding.setOnclickListener(this);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_save:
                savedata();
                break;
            case R.id.detail_ProductTime:
                DatePickerDialog dpd2 = new DatePickerDialog(getContext(), Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;
            case R.id.detail_InspectTime:
                DatePickerDialog dpd = new DatePickerDialog(getContext(), Datelistener2, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();
                break;
            case R.id.btn_back:
                getFragmentManager().popBackStack();
                break;
        }
    }
    private void getdata(String s){
        Map<String,String> maps=new HashMap<>();
        maps.put("opType","getPurchaseInfo");
        maps.put("ContractNo",s);
        Zhijian_Net.getPurchaseInfo(getContext(), maps, new Zhijian_Net.GetSingData() {
            @Override
            public void success(Object s) {
                producerNames.clear();
                fabricCodes.clear();

                PurchaseInfo purchaseInfo=(PurchaseInfo )s;
                ArrayList<String> fabricNames=new ArrayList<>();
                if (heardItem_2 != null) {
                    fabricNames.add(heardItem_2.getFabricName());
                    fabricCodes.add(heardItem_2.getFabricCode());
                    binding.detailSupplierName.setText(heardItem_2.getSupplierName());
//                    heardItem_2.getSupplierCode();
                    binding.detailProducerName.setText(heardItem_2.getProducerName());
                    producerCode=heardItem_2.getProducerCode();
                    binding.detailInspectorName.setText(heardItem_2.getInspectorName());
                }else{
                    binding.detailSupplierName.setText(purchaseInfo.getSupplierTable().get(0).getMs_gys());
                    producerCode=purchaseInfo.getProducerTable().get(0).getcVenCode();
                    binding.detailProducerName.setText(producerCode+"|"+purchaseInfo.getProducerTable().get(0).getcVenName());
                    binding.detailInspectorName.setText(Data.ZHIJIAN_Account);
                }
                for (int i = 0; i <purchaseInfo.getFrabricTable().size() ; i++) {
                    fabricNames.add(purchaseInfo.getFrabricTable().get(i).getText());
                    fabricCodes.add(purchaseInfo.getFrabricTable().get(i).getValue());
                }
                ArrayAdapter<String> adapter=new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_dropdown_item,fabricNames);
//                producerCode=purchaseInfo.getProducerTable().get(0).getcVenCode();
                binding.detailFabricName.setAdapter(adapter);
//                producerNames.add(producerCode+"|"+purchaseInfo.getProducerTable().get(0).getcVenName());
//                producerCodes.add(producerCode);

            }
        });
        getproducerNames();
        getEngineerInfo();
    }
    private void getproducerNames(){
        Zhijian_Net.gethetonghao2(getContext(), new Zhijian_Net.GetSingData<List<HeTongHao>>() {
            @Override
            public void success(List<HeTongHao> s) {
                for (HeTongHao hetonghao:
                     s) {
                    producerNames.add(hetonghao.getText());
                    producerCodes.add(hetonghao.getValue());
                }
                produceradapter=new FilterAdapter<String>(getContext(),producerNames);
                binding.detailProducerName.setAdapter(produceradapter);
            }
        });

    }
    private void getEngineerInfo(){
        getEngineerInfonames.clear();
        getEngineerInfocodes.clear();
        Zhijian_Net.getEngineerInfo(getContext(), new Zhijian_Net.GetSingData<List<HeTongHao>>() {
            @Override
            public void success(List<HeTongHao> s) {
                if (heardItem_2!=null){
                    getEngineerInfonames.add(heardItem_2.getEngineerName());
                    getEngineerInfocodes.add(heardItem_2.getEngineerNo());
                }
                for (HeTongHao hetonghao:
                        s) {
                    getEngineerInfonames.add(hetonghao.getText());
                    getEngineerInfocodes.add(hetonghao.getValue());
                }
                supplierInfoadapter=new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_dropdown_item,getEngineerInfonames);
                binding.detailEngineerNo.setAdapter(supplierInfoadapter);
            }
        });
    }


    private void getReasonRemark(String value,String reason){
        reasonMarkList.clear();
        Map<String,String> maps=new HashMap<>();
        maps.put("Result",value);
        Zhijian_Net.getReasonRemark(getContext(), maps,new Zhijian_Net.GetSingData<List<ReasonRemark>>() {
            @Override
            public void success(List<ReasonRemark> s) {
                for (ReasonRemark reasonRemark : s) {
                    reasonMarkList.add(reasonRemark.getValue());
                }

                int pos = reasonMarkList.indexOf(reason);

                reasonMarkadapter=new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_dropdown_item,reasonMarkList);
                binding.detailReasonMarkSp.setAdapter(reasonMarkadapter);
                binding.detailReasonMarkSp.setSelection(pos);
                reasonMarkadapter.notifyDataSetChanged();
            }
        });
    }

    private void savedata(){
        Map<String,String> maps=new HashMap<>();
        maps.put("opType","saveEInspectHead");
        maps.put("Guid",guid);
        maps.put("ID",id);
        maps.put("OffID",offid);
        maps.put("OffCount",OffCount);

        maps.put("FormNumber",formnumber);
        maps.put("FabricCode",fabricCode);
        maps.put("FabricName",binding.detailFabricName.getSelectedItem().toString());
        maps.put("ContractNo",binding.detailContractNo.getText().toString());
        maps.put("ProducerCode",producerCode);

        maps.put("ProducerName",binding.detailProducerName.getText().toString());
        maps.put("SupplierCode",supplierCode);
        maps.put("SupplierName",binding.detailSupplierName.getText().toString());
        maps.put("InsType",binding.detailInsType.getSelectedItem().toString());
        maps.put("SamplingNo",binding.detailSamplingNo.getText().toString());

        maps.put("EngineerNo",engineerNocode);
        maps.put("Color",binding.detailColor.getText().toString());
        maps.put("GateWidth",binding.detailGateWidth.getText().toString());
        maps.put("BatchNumber",binding.detailBatchNumber.getText().toString());
        maps.put("ProductTime",binding.detailProductTime.getText().toString());

        maps.put("InspectorName",binding.detailInspectorName.getText().toString());
        maps.put("InspectTime",binding.detailInspectTime.getText().toString());
        maps.put("InspectResult",binding.detailInspectResult.getSelectedItem().toString());
        maps.put("Remark",binding.detailRemark.getText().toString());
        maps.put("CreateUser","系统管理员");//Data.username

        maps.put("ResultDes",reasonType == 0?binding.detailReasonMark.getText().toString():reasonRemark);
        maps.put("Usefor",binding.detailUsefor.getSelectedItem().toString());

        for (Iterator<Map.Entry<String, String>> it = maps.entrySet().iterator(); it.hasNext();){
            Map.Entry<String, String> item = it.next();

            if(StringUtils.isEmpty(item.getValue())){
                it.remove();
            }

        }
        Zhijian_Net.saveEInspectHead(getContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                Log.e(TAG, "success: "+s.get(0).getTip() );
                toast(s.get(0).getTip());
                getFragmentManager().popBackStack();
            }
        });
    }

    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month="";
            String day="";
            if (monthOfYear<9){
                month="0"+(monthOfYear+1);
            }else {
                month=""+(monthOfYear+1);
            }
            if (dayOfMonth<10){
                day="0"+dayOfMonth;
            }else {
                day=""+dayOfMonth;
            }
           binding.detailProductTime.setText(myyear + "-" +month + "-" + day);
        }
    };
    private DatePickerDialog.OnDateSetListener Datelistener2 = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month="";
            String day="";
            if (monthOfYear<9){
                month="0"+(monthOfYear+1);
            }else {
                month=""+(monthOfYear+1);
            }
            if (dayOfMonth<10){
                day="0"+dayOfMonth;
            }else {
                day=""+dayOfMonth;
            }
            binding.detailInspectTime.setText(myyear + "-" +month + "-" + day);
        }
    };

}
